package com.example.hotel_lxy.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;


import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.EventBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.GetUserBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.dialog.EditionDialog;
import com.example.hotel_lxy.ui.fragment.FragmentHome;
import com.example.hotel_lxy.ui.fragment.FragmentHome2;
import com.example.hotel_lxy.ui.fragment.FragmentMarketing;
import com.example.hotel_lxy.ui.fragment.FragmentMy;
import com.example.hotel_lxy.ui.fragment.FragmentOrder;
import com.example.hotel_lxy.ui.fragment.FragmentReserve;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.BaseFragment;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 首页
 */
@Route(path = "/main/MainActivity")
public class MainActivity extends BaseActivity {

    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_order)
    RadioButton rbOrder;
    @BindView(R.id.rb_markting)
    RadioButton rbMarkting;
    @BindView(R.id.rb_my)
    RadioButton rbMy;
    @BindView(R.id.line_reserve)
    LinearLayout lineReserve;
    @BindView(R.id.fl_layout)
    FrameLayout flLayout;
    private int position = 0;
    private int page = 0;
    private Fragment tempFragment;
    @Autowired
    String pos;
    //fragment集合
    private List<BaseFragment> fragments = new ArrayList<>();

    public static void start(String pos) {
        ARouter.getInstance().build(ARouterPath.getMainActivity())
                .withString("pos", pos)
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);  //事件的注册
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); //解除注册
    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBean carrier) {
        if (position != 0) {
//            position=0;
//            showDateRb(true, false, false, false);
            page = 1;
        }
    }


    @Override
    public void doWork() {
        super.doWork();
        judgePermission();
        ARouter.getInstance().inject(this);
        String string = SPUtils.get(MainActivity.this, "currentDate", "").toString();
        if (string.equals("")) {
            DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date(System.currentTimeMillis());//获取当前时间
            String currentDate = simpleDateFormat.format(date);
            SPUtils.put(MainActivity.this, "currentDate", "" + currentDate);
        } else {
            SPUtils.put(MainActivity.this, "currentDate", "" + string);
        }
//        position = Integer.valueOf(pos);
//        showDateRb(true, false, false, false);

        fragments.add(new FragmentHome2());//首页
        fragments.add(new FragmentOrder());//订单
        fragments.add(new FragmentReserve());//预定
        fragments.add(new FragmentMarketing());//营销
        fragments.add(new FragmentMy());//我的
        BaseFragment baseFragment = getFragment(position);


        /**
         * 第一个参数: 上次显示的Fragment
         * 第二个参数: 当前正要显示的Fragment
         */
        switchFragment(tempFragment, baseFragment);
        //版本更新
//        EditionDialog.show(this,null);
//        SPUtils.put(MainActivity.this,"aBoolean","1");

    }
    protected void judgePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            //手机状态权限
            String[] SdCdPermission = {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE ,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_CONTACTS,
                    Manifest.permission.CALL_PHONE};
            if (ContextCompat.checkSelfPermission(this, SdCdPermission[0]) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, SdCdPermission[1]) != PackageManager.PERMISSION_GRANTED||
                    ContextCompat.checkSelfPermission(this, SdCdPermission[2]) != PackageManager.PERMISSION_GRANTED||
                    ContextCompat.checkSelfPermission(this, SdCdPermission[3]) != PackageManager.PERMISSION_GRANTED||
                    ContextCompat.checkSelfPermission(this, SdCdPermission[4]) != PackageManager.PERMISSION_GRANTED||
                    ContextCompat.checkSelfPermission(this, SdCdPermission[5]) != PackageManager.PERMISSION_GRANTED||
                    ContextCompat.checkSelfPermission(this, SdCdPermission[6]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCdPermission, 350);
            }
        }

    }
    @Override
    protected void onResume() {
        super.onResume();
        // showGetUser();
        if (page == 1) {
            page = 0;
            position = 0;
            showDateRb(true, false, false, false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // showGetUser();
    }

    private void showGetUser() {
        OkHttpUtils.post()
                .url(Api.POST_USER_GETUSER)
                .addHeader("flag", SPUtils.get(MainActivity.this, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "个人信息Exception~~~~~~~~    " + e.getMessage());
                        hideLoadingDialog();

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "个人信息onResponse~~~~~~~~    " + response);
                        BeanBean beanBean = JsonUtils.parseObject(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            GetUserBean getUserBean = JsonUtils.parseObject(response, GetUserBean.class);
                            //仅查看销控表
                            SPUtils.put(MainActivity.this, "xiaokongbiao", "" + getUserBean.getData().getRole().getXiaokongbiao() + "");
                            //是否开启零点功能  1开启  0关闭
                            SPUtils.put(MainActivity.this, "notenabled", "" + getUserBean.getData().getRole().getNotenabled());
                            //是否可以零点新增预定
                            SPUtils.put(MainActivity.this, "addzero", "" + getUserBean.getData().getRole().getAddzero());
                            //选择客户经理
                            SPUtils.put(MainActivity.this, "szkehujl", "" + getUserBean.getData().getRole().getSzkehujl());
                            //是否可以新增预定
                            SPUtils.put(MainActivity.this, "addscheduled", "" + getUserBean.getData().getRole().getAddscheduled());
                            //仅查看零点销控表
                            SPUtils.put(MainActivity.this, "jcklingdianck", "" + getUserBean.getData().getRole().getJcklingdianck());
                            //零点选择预订人
                            SPUtils.put(MainActivity.this, "xzyudingren", "" + getUserBean.getData().getRole().getXzyudingren());
                            //不启用零点  1开启  0关闭
                            SPUtils.put(MainActivity.this, "notenabled", "" + getUserBean.getData().getRole().getNotenabled());
                            //零点查看全部  1开启  0关闭
                            SPUtils.put(MainActivity.this, "ldchakanqb", "" + getUserBean.getData().getRole().getLdchakanqb());
                            //是否可以零点修改个人  1开启  0关闭
                            SPUtils.put(MainActivity.this, "ldmodifypersonal", "" + getUserBean.getData().getRole().getLdmodifypersonal());
                            //是否可以零点修改全部  1开启  0关闭
                            SPUtils.put(MainActivity.this, "ldmodifyall", "" + getUserBean.getData().getRole().getLdmodifyall());
                            //是否可以零点退订全部  1开启  0关闭
                            SPUtils.put(MainActivity.this, "retreatall", "" + getUserBean.getData().getRole().getRetreatall());
                            //是否可以零点退订个人  1开启  0关闭
                            SPUtils.put(MainActivity.this, "retreatpersonal", "" + getUserBean.getData().getRole().getRetreatpersonal());
                            //是否可以零点入座全部  1开启  0关闭
                            SPUtils.put(MainActivity.this, "seatall", "" + getUserBean.getData().getRole().getSayall());
                            //是否可以零点入座个人  1开启  0关闭
                            SPUtils.put(MainActivity.this, "seatpersonal", "" + getUserBean.getData().getRole().getSeatpersonal());
                            //是否可以零点翻台全部  1开启  0关闭
                            SPUtils.put(MainActivity.this, "overturnall", "" + getUserBean.getData().getRole().getOverturnall());
                            //是否可以零点翻台个人  1开启  0关闭
                            SPUtils.put(MainActivity.this, "overturnpersonal", "" + getUserBean.getData().getRole().getOverturnpersonal());
                            //查看全部营销订单1开启  0关闭
                            SPUtils.put(MainActivity.this, "ckqbyingxiao", "" + getUserBean.getData().getRole().getCkqbyingxiao());
                            //是否可以查看全部  1开启  0关闭
                            SPUtils.put(MainActivity.this, "sayall", "" + getUserBean.getData().getRole().getSayall());
                            //是否可以查看个人  1开启  0关闭
                            SPUtils.put(MainActivity.this, "saypersonal", "" + getUserBean.getData().getRole().getSaypersonal());

                            //是否可以查看TOP榜  1开启  0关闭
                            SPUtils.put(MainActivity.this, "saytop", "" + getUserBean.getData().getRole().getSaytop());
                            //营销查看全部回访  1开启  0关闭
                            SPUtils.put(MainActivity.this, "sayvisitall", "" + getUserBean.getData().getRole().getSayvisitall());
                            //营销添加回访  1开启  0关闭
                            SPUtils.put(MainActivity.this, "addvisit", "" + getUserBean.getData().getRole().getAddvisit());

                            //查看全部宴会数据  1开启  0关闭
                            SPUtils.put(MainActivity.this, "saybanquetdata", "" + getUserBean.getData().getRole().getSaybanquetdata());
                            //查看全部零点数据  1开启  0关闭
                            SPUtils.put(MainActivity.this, "sayzerodata", "" + getUserBean.getData().getRole().getSayzerodata());
                            //查看全部宴会客户  1开启  0关闭
                            SPUtils.put(MainActivity.this, "banquetclient", "" + getUserBean.getData().getRole().getBanquetclient());
                            //查看全部零点客户  1开启  0关闭
                            SPUtils.put(MainActivity.this, "zeroclient", "" + getUserBean.getData().getRole().getZeroclient());
                            //修改全部宴会客户
                            SPUtils.put(MainActivity.this, "modifybanquet", "" + getUserBean.getData().getRole().getModifybanquet());
                            //修改全部零点客户
                            SPUtils.put(MainActivity.this, "modifyzero", "" + getUserBean.getData().getRole().getModifyzero());


                            //确认方式
                            SPUtils.put(MainActivity.this, "config", "1");
                            SPUtils.put(MainActivity.this, "hotel_mobile", "" + getUserBean.getData().getList().getHotel_mobile());

                            SPUtils.put(MainActivity.this, "hotel_addr", "" + getUserBean.getData().getList().getHotel_addr());
                            SPUtils.put(MainActivity.this, "hotel", "" + getUserBean.getData().getList().getHotel());

                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(MainActivity.this, "token", "");
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            finish();
                        }

                    }
                });
    }

    @OnClick({R.id.rb_home, R.id.rb_order, R.id.line_reserve, R.id.rb_markting, R.id.rb_my})
    public void onViewClicked(View view) {
        String xiaokongbiao = SPUtils.get(MainActivity.this, "xiaokongbiao", "").toString();
        switch (view.getId()) {
            case R.id.rb_home://首页
                position = 0;
                showDateRb(true, false, false, false);
                break;
            case R.id.rb_order://订单
                if (xiaokongbiao.equals("1")) {
                    ToastUtils.longToast(MainActivity.this, "当前账号没有操作权限哦");
                    rbOrder.setChecked(false);
                    rbMarkting.setChecked(false);
                    rbMy.setChecked(false);
                    return;
                }
                position = 1;
                showDateRb(false, true, false, false);
                break;
            case R.id.line_reserve://预定
                if (xiaokongbiao.equals("1")) {
                    ToastUtils.longToast(MainActivity.this, "当前账号没有操作权限哦");
                    rbOrder.setChecked(false);
                    rbMarkting.setChecked(false);
                    rbMy.setChecked(false);
                    return;
                }
                boolean addscheduled = JurisdictionUtils.getAddscheduled(MainActivity.this);
                if (!addscheduled) {
                    ToastUtils.longToast(MainActivity.this, "当前账号没有操作权限哦");
                    return;
                }
                position = 2;
                rbHome.setChecked(rbHome.isChecked());
                rbOrder.setChecked(rbOrder.isChecked());
                rbMarkting.setChecked(rbMarkting.isChecked());
                rbMy.setChecked(rbMy.isChecked());
                SimpleDateFormat formatter_y = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                String begin_year = formatter_y.format(curDate);
                String string = SPUtils.get(MainActivity.this, "sched_id", "").toString();
                ReserveActivity.start(string, begin_year + "-null");//预定
                break;
            case R.id.rb_markting://营销
                if (xiaokongbiao.equals("1")) {
                    ToastUtils.longToast(MainActivity.this, "当前账号没有操作权限哦");
                    rbOrder.setChecked(false);
                    rbMarkting.setChecked(false);
                    rbMy.setChecked(false);
                    return;
                }
                position = 3;
                showDateRb(false, false, true, false);
                break;
            case R.id.rb_my://我的
//                if(xiaokongbiao.equals("1")){
//                    ToastUtils.longToast(MainActivity.this,"当前账号没有操作权限哦");
//                    rbOrder.setChecked(false);
//                    rbMarkting.setChecked(false);
//                    rbMy.setChecked(false);
//                    return;
//                }
                position = 4;
                showDateRb(false, false, false, true);
                break;

        }
    }

    private void showDateRb(boolean b, boolean b2, boolean b3, boolean b4) {
        rbHome.setChecked(b);
        rbOrder.setChecked(b2);
        rbMarkting.setChecked(b3);
        rbMy.setChecked(b4);
        //根据位置得到相应的Fragment
        BaseFragment baseFragment = getFragment(position);
        /**
         * 第一个参数: 上次显示的Fragment
         * 第二个参数: 当前正要显示的Fragment
         */
        switchFragment(tempFragment, baseFragment);
    }

    /**
     * 根据位置得到对应的 Fragment
     *
     * @param position
     * @return
     */
    private BaseFragment getFragment(int position) {
        if (fragments != null && fragments.size() > 0) {
            BaseFragment baseFragment = (BaseFragment) fragments.get(position);
            return baseFragment;
        }
        return null;
    }

    /**
     * 切换Fragment
     *
     * @param fragment
     * @param nextFragment
     */
    private void switchFragment(Fragment fragment, BaseFragment nextFragment) {
        if (tempFragment != nextFragment) {
            tempFragment = nextFragment;
            if (nextFragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判断nextFragment是否添加成功
                if (!nextFragment.isAdded()) {
                    //隐藏当前的Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    //添加Fragment
                    transaction.add(R.id.fl_layout, nextFragment).commit();
                } else {
                    //隐藏当前Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }


    /**
     * 保存MyTouchListener接口的列表
     */
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<>();

    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     */
    public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }

    /**
     * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
     */
    public void unRegisterMyTouchListener(MyTouchListener listener) {
        myTouchListeners.remove(listener);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public interface MyTouchListener {
        /**
         * onTOuchEvent的实现
         *
         * @return
         */
        boolean onTouchEvent(MotionEvent event);
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 2000) {
                System.exit(0);
            } else {
                Toast.makeText(getApplicationContext(), "再按一次返回键退出", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


}